import React from 'react'
import { useState, useEffect } from 'react'

import LinkButton from '../LinkButton'

import { reqWeather } from '../../api'
import { formateDate } from '../../utils/dateUtils'

import './index.less'

export default function Header() {
    // 当前时间
    const [currentTime, setCurrentTime] = useState(formateDate("YYYY-mm-dd HH:MM:SS",Date.now()))
    // 当前天气
    const [weather, setWeather] = useState()


    // 获取当前时间
    // 启动定时器，每隔1s更新一次currentTime
    const getTime = () => {
        setInterval(() => {
            setCurrentTime(formateDate("YYYY-mm-dd HH:MM:SS",Date.now()))
        }, 1000)
    }

    // 获取天气情况
    // 发送异步ajax请求，获取天气书记并更新状态
    const getWeather = async () => {
        const weather = await reqWeather("武汉")
        setWeather(weather)
    }


    // 退出登录
    const logout = () => {
        alert("1111")
    }


    useEffect(() => {
        //  类似于componentDidMount(){}
        getTime()

        // 类似于componentWillUnmount(){}
        return () => {
            clearInterval(getTime);
        }
    }, [currentTime])


    useEffect(() => {
        // console.log("这是模拟componentDidMount钩子函数")
        getWeather()
        return () => {
            //return出来的函数本来就是更新前，销毁前执行的函数，现在不监听任何状态，所以只在销毁前执行
            // console.log("这是模拟componentWillUnmount钩子函数")
        }
    }, [])



    return (
        <div className="header">
            <div className="header-top">
                <span>欢迎,</span>
                <LinkButton onClick={logout}>退出</LinkButton>
            </div>
            <div className="header-bottom">
                <div className="header-bottom-left">标&nbsp;题</div>
                <div className="header-bottom-right">
                    <span>{currentTime}</span>
                    <img src={weather?.dayPictureUrl} alt="weather" />
                    <span>{weather?.weather}</span>
                </div>
            </div>
        </div>
    )
}
